package controller

import (
	"github.com/gin-gonic/gin"
	"shop-bean/constant"
	"shop-bean/dto"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils"
	"shop-common/utils/contextArgs"
	"shop-common/utils/queryWrapper"
	"shop-service/business"
	"strings"
	"time"
)

type CategoryController struct {
}

// @Tags 分类管理
// @Summary 获取全部分类
// @Security ApiKeyAuth
// @function: List
// @Accept  json
// @Produce  json
// @Param type query int true "分类类型 1 产品分类，2 附件分类"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/category/list [get]
func (c *CategoryController) List(ctx *gin.Context) {
	_type, err := contextArgs.GetUriIntQuery(ctx, "type")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var categorys []*dto.CategoryDTO
	list, err := business.ServiceImpl().CategoryService.Find(ctx, constant.SHOP_ID, int(_type))
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	for _, category := range list {
		ids := strings.Split(category.AttIds, ",")
		var attachmentDTO []*dto.AttachmentDTO
		if len(ids) > 0 {
			variables.GormDB().Model(&model.Attachment{}).Find(&attachmentDTO, ids)
			categorys = append(categorys, &dto.CategoryDTO{
				CategoryId:   category.CategoryId,
				ParentId:     category.ParentId,
				CategoryName: category.CategoryName,
				Attachment:   attachmentDTO,
				Pic:          category.Pic,
				Seq:          category.Seq,
				Status:       category.Status,
			})
		}
	}

	serializer.SuccessData(ctx, "", categorys)
}

// @Tags 分类管理
// @Summary 获取分类信息
// @Security ApiKeyAuth
// @function: Info
// @Param categoryId path string true "分类ID"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/category/info/{categoryId} [get]
func (c *CategoryController) Info(ctx *gin.Context) {
	categoryId, err := contextArgs.GetUriIntPath(ctx, "categoryId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	category, err := business.ServiceImpl().CategoryService.FindById(ctx, uint(categoryId))
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", category)
}

// @Tags 分类管理
// @description: 新增分类
// @Summary 新增分类
// @Security ApiKeyAuth
// @function: Save
// @Accept  json
// @Produce  json
// @Param data body request.CategoryRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/category [post]
func (c *CategoryController) Save(ctx *gin.Context) {
	form := request.CategoryRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	pair := queryWrapper.Eq("category_name", form.CategoryName)
	pair = pair.And(queryWrapper.Eq("shop_id", constant.SHOP_ID))
	info, err := findOneCategory(ctx, pair)
	if err != nil {
		serializer.Fail(ctx, "新增分类失败！")
		return
	}

	if info.CategoryId > 0 {
		serializer.Fail(ctx, "类目名称已存在！")
		return
	}

	err = business.ServiceImpl().CategoryService.Create(ctx, &model.Category{
		ShopId:       constant.SHOP_ID,
		Type:         form.Type,
		ParentId:     form.ParentId,
		CategoryName: form.CategoryName,
		FileId:       form.FileId,
		AttIds:       form.AttIds,
		Pic:          form.Pic,
		Seq:          form.Seq,
		Status:       form.Status,
		RecAt:        time.Now(),
	}, form.FileId)
	if err != nil {
		serializer.Fail(ctx, "新增分类失败！")
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 分类管理
// @description: 编辑分类
// @Summary 编辑分类
// @Security ApiKeyAuth
// @function: Update
// @Accept  json
// @Produce  json
// @Param data body request.CategoryRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/category [put]
func (c *CategoryController) Update(ctx *gin.Context) {
	form := request.CategoryRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if form.CategoryId == 0 {
		serializer.Fail(ctx, "Id不能为空")
		return
	}

	if form.CategoryId == form.ParentId {
		serializer.Fail(ctx, "分类的上级不能是自己本身")
		return
	}

	pair := queryWrapper.Eq("category_name", form.CategoryName)
	pair = pair.And(queryWrapper.Eq("shop_id", constant.SHOP_ID))
	//info, err := findOneCategory(pair)
	//if err != nil {
	//	variables.ErrLogger.Sugar().Error("findOneCategory err: %v, pair: %+v ", err, pair)
	//	serializer.Fail(ctx, "更新分类失败！")
	//	return
	//}
	//
	//if info.CategoryId > 0 {
	//	serializer.Fail(ctx, "类目名称已存在！")
	//	return
	//}

	categoryDB, err := business.ServiceImpl().CategoryService.FindById(ctx, form.CategoryId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	//如果从下线改成正常，则需要判断上级的状态
	if categoryDB != nil && categoryDB.Status == constant.GLOBAL_DISABLE && form.Status == constant.GLOBAL_ENABLE && form.ParentId != 0 {
		wp := queryWrapper.Eq("category_id", form.CategoryId)
		wp = pair.And(queryWrapper.Eq("parent_id", form.ParentId))
		parentCategory, err := findOneCategory(ctx, wp)
		if err != nil {
			serializer.Fail(ctx, serializer.PublicUpdateErr)
			return
		}

		if parentCategory.ParentId > 0 || parentCategory.Status == constant.GLOBAL_DISABLE {
			serializer.Fail(ctx, "修改失败，上级分类不存在或者不为正常状态！")
			return
		}
	}

	var oldPic string
	oldInfo, err := findByIdCategory(ctx, form.CategoryId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	if oldInfo != nil {
		oldPic = oldInfo.Pic
	}

	var category model.Category
	utils.StructMap(&form, &category)

	err = business.ServiceImpl().CategoryService.Updates(ctx, &category, oldPic)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 分类管理
// @description: 删除分类
// @Summary 删除分类
// @Security ApiKeyAuth
// @function: Delete
// @Accept  json
// @Produce  json
// @Param categoryId path int true "分类Id"
// @Param categoryName query string true "分类名称"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/category/{categoryId} [delete]
func (c *CategoryController) Delete(ctx *gin.Context) {
	categoryId, err := contextArgs.GetUriIntPath(ctx, "categoryId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	// 查询父级
	parentCategory, err := findOneCategory(ctx, queryWrapper.Eq("parent_id", categoryId))
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}
	if parentCategory.CategoryId > 0 {
		serializer.Fail(ctx, "请删除子分类，再删除该分类!")
		return
	}

	category, err := findByIdCategory(ctx, uint(categoryId))

	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}
	if category == nil {
		serializer.Fail(ctx, "无可删除数据!")
		return
	}

	// 查询子级
	err = business.ServiceImpl().CategoryService.Delete(ctx, uint(categoryId), category.Pic)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}
	serializer.Success(ctx, "")
}

func findOneCategory(ctx *gin.Context, pair *queryWrapper.WherePair) (category *model.Category, err error) {
	return business.ServiceImpl().CategoryService.FindOne(ctx, pair)
}

func findByIdCategory(ctx *gin.Context, id uint) (category *model.Category, err error) {
	return business.ServiceImpl().CategoryService.FindById(ctx, id)
}
